﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Table;
using OfficeOpenXml.Drawing.Chart;

namespace SIGERP_Presentacion
{
    public partial class BotonAExcel : System.Windows.Forms.Button
    {
        public BotonAExcel()
        {
            InitializeComponent();
        }

        public void GenerateExcelWithCharts(DataTable dataToExcel, string fileName)
        {
            if (dataToExcel.Rows.Count > 0)
            {
                string currentDirectorypath = Environment.CurrentDirectory;
                string finalFileNameWithPath = string.Empty;
                string excelSheetName = "Libro1";
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.FileName = fileName;
                saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {



                    fileName = saveDialog.FileName;
                    finalFileNameWithPath = saveDialog.FileName;

                    //Delete existing file with same file name.
                    if (File.Exists(finalFileNameWithPath))
                        File.Delete(finalFileNameWithPath);

                    var newFile = new FileInfo(finalFileNameWithPath);

                    using (var package = new ExcelPackage(newFile))
                    {
                        //Add a new table from the given datatable and start loading table form A1 cell.
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(excelSheetName);

                        //Add a new table from the given datatable
                        worksheet.Cells["A1"].LoadFromDataTable(dataToExcel, true, TableStyles.Light1);
                        worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
                        //Save all changes to excel sheet
                        package.Save();

                        MessageBox.Show(string.Format("Archivo '{0}' generado correctamente.", fileName)
                            , "El archivo se guardó correctamente", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }
    }
}
